<?php
/**
 * Style Integration Manager
 * 样式集成管理器
 * 
 * 确保HTML模板样式正确应用到WordPress模板
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit; // 禁止直接访问
}

/**
 * 样式集成主函数
 */
function wbw_integrate_template_styles() {
    // 添加主题支持
    add_theme_support('woocommerce');
    add_theme_support('wc-product-gallery-zoom');
    add_theme_support('wc-product-gallery-lightbox');
    add_theme_support('wc-product-gallery-slider');
    
    // 设置WooCommerce图片尺寸
    wbw_set_woocommerce_image_sizes();
    
    // 应用自定义样式
    wbw_apply_custom_styles();
    
    // 集成Bootstrap样式
    wbw_integrate_bootstrap_styles();
}
add_action('after_setup_theme', 'wbw_integrate_template_styles');

/**
 * 设置WooCommerce图片尺寸
 */
function wbw_set_woocommerce_image_sizes() {
    // 单个产品图片
    update_option('woocommerce_single_image_width', 600);
    
    // 缩略图尺寸
    update_option('woocommerce_thumbnail_image_width', 300);
    
    // 产品缩略图裁剪
    update_option('woocommerce_thumbnail_cropping', '1:1');
    
    // 产品画廊缩略图
    add_image_size('woocommerce_gallery_thumbnail', 100, 100, true);
    
    // 产品列表图片
    add_image_size('woocommerce_shop_catalog', 300, 300, true);
    
    // 单个产品大图
    add_image_size('woocommerce_single', 600, 600, true);
}

/**
 * 应用自定义样式
 */
function wbw_apply_custom_styles() {
    // 移除默认WooCommerce样式
    add_filter('woocommerce_enqueue_styles', '__return_empty_array');
    
    // 在头部添加自定义CSS
    add_action('wp_head', 'wbw_custom_css_output');
    
    // 添加body类
    add_filter('body_class', 'wbw_body_classes');
}

/**
 * 输出自定义CSS
 */
function wbw_custom_css_output() {
    $custom_css = _xin('custom_css', '');
    if (!empty($custom_css)) {
        echo '<style type="text/css">' . wp_strip_all_tags($custom_css) . '</style>';
    }
    
    // 输出主题配色方案
    wbw_output_color_scheme();
    
    // 输出动态样式
    wbw_output_dynamic_styles();
}

/**
 * 输出主题配色方案
 */
function wbw_output_color_scheme() {
    $primary_color = _xin('primary_color', '#007cba');
    $secondary_color = _xin('secondary_color', '#005a8b');
    $accent_color = _xin('accent_color', '#28a745');
    
    echo '<style type="text/css">';
    echo ':root {';
    echo '--theme-primary: ' . esc_attr($primary_color) . ';';
    echo '--theme-secondary: ' . esc_attr($secondary_color) . ';';
    echo '--theme-accent: ' . esc_attr($accent_color) . ';';
    echo '}';
    echo '</style>';
}

/**
 * 输出动态样式
 */
function wbw_output_dynamic_styles() {
    echo '<style type="text/css">';
    
    // 商店列数设置
    $shop_columns = _xin('shop_columns', 4);
    echo '.woocommerce ul.products { grid-template-columns: repeat(' . intval($shop_columns) . ', 1fr); }';
    
    // 侧边栏位置
    $sidebar_position = _xin('shop_sidebar_position', 'left');
    if ($sidebar_position === 'right') {
        echo '.shop-layout { flex-direction: row-reverse; }';
    }
    
    // 自定义字体设置
    $custom_font_family = _xin('custom_font_family', '');
    if (!empty($custom_font_family)) {
        echo 'body, .woocommerce { font-family: ' . esc_attr($custom_font_family) . '; }';
    }
    
    echo '</style>';
}

/**
 * 添加body类
 */
function wbw_body_classes($classes) {
    // 添加主题类
    $classes[] = 'wp-bootstrap-woo';
    
    // 添加首页模板类
    if (is_front_page()) {
        $homepage_template = get_current_homepage_template();
        $classes[] = 'homepage-' . $homepage_template;
    }
    
    // 添加WooCommerce页面类
    if (class_exists('WooCommerce')) {
        if (is_shop()) {
            $classes[] = 'woo-shop-page';
        } elseif (is_product()) {
            $classes[] = 'woo-product-page';
        } elseif (is_cart()) {
            $classes[] = 'woo-cart-page';
        } elseif (is_checkout()) {
            $classes[] = 'woo-checkout-page';
        } elseif (is_account_page()) {
            $classes[] = 'woo-account-page';
        }
    }
    
    // 添加侧边栏类
    if (_xin('enable_shop_sidebar', true) && (is_shop() || is_product_category() || is_product_tag())) {
        $sidebar_position = _xin('shop_sidebar_position', 'left');
        $classes[] = 'has-shop-sidebar';
        $classes[] = 'sidebar-' . $sidebar_position;
    }
    
    return $classes;
}

/**
 * 集成Bootstrap样式
 */
function wbw_integrate_bootstrap_styles() {
    // 添加Bootstrap兼容性类
    add_filter('nav_menu_css_class', 'wbw_nav_menu_classes', 10, 2);
    add_filter('nav_menu_link_attributes', 'wbw_nav_menu_link_attributes', 10, 4);
    
    // 集成Bootstrap网格系统
    add_action('wp_footer', 'wbw_bootstrap_grid_integration');
}

/**
 * 导航菜单Bootstrap类
 */
function wbw_nav_menu_classes($classes, $item) {
    if (in_array('menu-item-has-children', $classes)) {
        $classes[] = 'dropdown';
    }
    return $classes;
}

/**
 * 导航菜单链接属性
 */
function wbw_nav_menu_link_attributes($atts, $item, $args, $depth) {
    if (in_array('menu-item-has-children', $item->classes)) {
        $atts['class'] = 'dropdown-toggle';
        $atts['data-bs-toggle'] = 'dropdown';
    }
    return $atts;
}

/**
 * Bootstrap网格系统集成
 */
function wbw_bootstrap_grid_integration() {
    ?>
    <script>
    // 自动为表格添加Bootstrap类
    document.addEventListener('DOMContentLoaded', function() {
        const tables = document.querySelectorAll('table');
        tables.forEach(function(table) {
            if (!table.classList.contains('table')) {
                table.classList.add('table', 'table-striped');
            }
        });
        
        // 为表单添加Bootstrap类
        const forms = document.querySelectorAll('form');
        forms.forEach(function(form) {
            const inputs = form.querySelectorAll('input[type="text"], input[type="email"], input[type="password"], input[type="number"], select, textarea');
            inputs.forEach(function(input) {
                if (!input.classList.contains('form-control')) {
                    input.classList.add('form-control');
                }
            });
            
            const buttons = form.querySelectorAll('button, input[type="submit"]');
            buttons.forEach(function(button) {
                if (!button.classList.contains('btn')) {
                    button.classList.add('btn', 'btn-primary');
                }
            });
        });
    });
    </script>
    <?php
}

/**
 * WooCommerce模板覆盖检查
 */
function wbw_check_template_overrides() {
    $template_files = array(
        'archive-product.php' => 'shop page',
        'single-product.php' => 'product page',
        'cart/cart.php' => 'cart page',
        'checkout/form-checkout.php' => 'checkout page',
        'myaccount/dashboard.php' => 'account dashboard',
        'myaccount/orders.php' => 'order history',
    );
    
    $missing_templates = array();
    
    foreach ($template_files as $file => $description) {
        $template_path = get_template_directory() . '/woocommerce/' . $file;
        if (!file_exists($template_path)) {
            $missing_templates[] = $description . ' (' . $file . ')';
        }
    }
    
    if (!empty($missing_templates) && current_user_can('manage_options')) {
        add_action('admin_notices', function() use ($missing_templates) {
            echo '<div class="notice notice-warning"><p>';
            echo '<strong>WP Bootstrap Woo:</strong> 以下WooCommerce模板文件缺失: ';
            echo implode(', ', $missing_templates);
            echo '</p></div>';
        });
    }
}
add_action('admin_init', 'wbw_check_template_overrides');

/**
 * 样式优化和压缩
 */
function wbw_optimize_styles() {
    if (_xin('optimize_css', false) && !_THEME_DEBUG) {
        // CSS压缩和合并
        add_action('wp_print_styles', 'wbw_compress_css');
    }
}
add_action('init', 'wbw_optimize_styles');

/**
 * 压缩CSS
 */
function wbw_compress_css() {
    global $wp_styles;
    
    if (is_admin()) {
        return;
    }
    
    $css_files = array();
    
    foreach ($wp_styles->queue as $handle) {
        $style = $wp_styles->registered[$handle];
        if ($style && strpos($style->src, get_template_directory_uri()) !== false) {
            $css_files[] = $handle;
        }
    }
    
    if (!empty($css_files)) {
        // 创建合并的CSS文件
        $combined_css = wbw_combine_css_files($css_files);
        
        if ($combined_css) {
            // 移除原有的CSS文件
            foreach ($css_files as $handle) {
                wp_dequeue_style($handle);
            }
            
            // 添加合并后的CSS
            wp_enqueue_style('wbw-combined', $combined_css, array(), _THEME_VERSION);
        }
    }
}

/**
 * 合并CSS文件
 */
function wbw_combine_css_files($handles) {
    $upload_dir = wp_upload_dir();
    $cache_dir = $upload_dir['basedir'] . '/wbw-cache/';
    $cache_url = $upload_dir['baseurl'] . '/wbw-cache/';
    
    if (!file_exists($cache_dir)) {
        wp_mkdir_p($cache_dir);
    }
    
    $cache_file = 'combined-' . md5(implode(',', $handles)) . '.css';
    $cache_path = $cache_dir . $cache_file;
    $cache_url_full = $cache_url . $cache_file;
    
    if (!file_exists($cache_path)) {
        global $wp_styles;
        $combined_content = '';
        
        foreach ($handles as $handle) {
            $style = $wp_styles->registered[$handle];
            if ($style) {
                $file_path = str_replace(get_template_directory_uri(), get_template_directory(), $style->src);
                if (file_exists($file_path)) {
                    $content = file_get_contents($file_path);
                    $combined_content .= wbw_minify_css($content) . "\n";
                }
            }
        }
        
        file_put_contents($cache_path, $combined_content);
    }
    
    return $cache_url_full;
}

/**
 * 压缩CSS内容
 */
function wbw_minify_css($css) {
    // 移除注释
    $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
    
    // 移除不必要的空白
    $css = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css);
    
    // 移除不必要的分号
    $css = str_replace(';}', '}', $css);
    
    return trim($css);
}

/**
 * 清理缓存文件
 */
function wbw_clear_style_cache() {
    $upload_dir = wp_upload_dir();
    $cache_dir = $upload_dir['basedir'] . '/wbw-cache/';
    
    if (file_exists($cache_dir)) {
        $files = glob($cache_dir . '*.css');
        foreach ($files as $file) {
            unlink($file);
        }
    }
}

/**
 * 主题更新时清理缓存
 */
add_action('after_switch_theme', 'wbw_clear_style_cache');
add_action('upgrader_process_complete', 'wbw_clear_style_cache');